import Vue from 'vue';
// 验证token是否失效
var expired = false;

// const domainName = '192.168.3.136:8080/pdos_admin';
// const domainName = 'zbz.intranet.hegao.net';
const domainName = 'lzs.cakemao.cn';
// const domainName = 'mk.51car.net/api/v1';

const host = 'https://' + domainName;
const socket = 'ws://' + domainName;

function request(url, param, way, res) {
	let token = uni.getStorageSync('token');
	uni.request({
		url: host + url,
		data: param,
		header: {
			'X-Api-Key': uni.getStorageSync('acess_token') || '',
			'Content-Type': "application/json" //传参类型
		},
		method: way,
		success: (data) => {
			// console.log(host + url)
			res(data.data)
		},
		fail: (e) => {
			console.log(e);
			res({
				data: {
				},
				success:false,
				msg:'请求失败'
			})
		}
	});
}

export default {
	init() {
		console.log("*** http installed ***");
		Vue.prototype.$http = {
			request: this.request,
			getHost: this.getHost,
			getSocket: this.getSocket,
			getlocal: this.getlocal,
		}
	},
	request: async function(url, param, way = 'POST', showLoading = true) {
		if (showLoading) {
			var inTime = setTimeout(() => {
				// uni.showLoading({
				// 	title: "正在加载",
				// 	mask: true
				// })
			}, 500)
		}
		return await new Promise(resolve => {
			request(url, param, way, (res) => {
				if (showLoading) {
					clearTimeout(inTime);
					uni.hideLoading();
				}
				if (res?.code == 401) {
					uni.clearStorageSync()
					uni.showModal({
						content: '身份已过期,请先登录',
						success: (res) => {
							if (res.confirm) {
								uni.switchTab({
									url: '/pages/user/user'
								})
							}
						},
						complete() {
							uni.clearStorageSync()
						}
					})
				}
				resolve(res)
			});
		})
	},
	getHost() {
		return host;
	},
	getSocket() {
		return socket;
	},
	getlocal() {
		return local;
	}
}
